<?php
declare (strict_types = 1);
namespace app\middleware;
use app\service\LogService;
class After
{
    public $ignoreKey =[
        "email_content",
        "content"
    ];
    /**
     * 处理请求增加请求日志
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        if (!empty($request->file())||strtolower($request->controller())=="login") {
            return $response;
        }
        $params = $request->post();
        foreach ($params as $key=>$val) {
            if (in_array($key,$this->ignoreKey)) {
                unset($params[$key]);
            }
        }
        $log =[
            "ip"=>$request->ip(),
            "method"=>$request->method(),
            "url"=>$request->url(),
            "action"=>$request->action(),
            "module"=>app('http')->getName(),
            "params"=>$request->isPost() ? json_encode($params,JSON_UNESCAPED_UNICODE):"",
            "user_id"=>$request->uid ?? 0,
            "user_name"=>$request->username ?? ""
        ];
         $service = app()->make(LogService::class);
         $service->save($log);
         return $response;
    }
}
